from sanic.views import HTTPMethodView
from sanic.response import json
from processing.other_func import ProToken,Sercret_all,Serialization,Random_id,date_format
import json as jn
from processing.Sql_DataFrom import ProJosn
from processing.comm import sqlPaging,sqlOrder,set_status,timestamp_to_standard,setTime

class setMealAdd(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json

        try:

            sql = """
                insert into set_meal(user_id,set_meal_money,set_meal_shop,title,details,set_meal_type,set_meal_type_id,sort,image,JSONData,status,create_time ) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,now()) 
            """

            db.insert(sql,(
                user_id,
                html_data['set_meal_money'] or '',
                html_data['set_meal_shop'] or '',
                html_data['title'] or '',
                html_data['details'] or '',
                html_data['set_meal_type'] or '',
                html_data['set_meal_type_id'] or '',
                html_data['sort'] or '',
                html_data['image'] or '',
                html_data['JSONData'] or '',
                html_data['status'] or '',
            ))
            return json({'code': 200, 'message': "添加成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/setMeal/add', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)
class setMealList(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json
        pageNum = int(request.args.get('pageNum'))
        pageSize = int(request.args.get('pageSize'))
        try:

            sql = """
               select user_id,set_meal_money,set_meal_shop,title,details,set_meal_type,set_meal_type_id,sort,image,JSONData,status,create_time from set_meal where user_id=%s
           """
            sql += f' ORDER BY create_time DESC '
            # 分页pageNum
            if pageNum == 1:
                sql += f" LIMIT {pageSize} "
            else:
                sql += f" LIMIT {pageNum * pageSize - pageSize},{pageNum * pageSize} "

            data = db.find_all(sql,(user_id))

            data = ProJosn(data,sql).to_dict(orient='records')

            return json({'code': 200, 'message': "请求成功!",'data':data})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/setMeal/list', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)
class setMealDel(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json

        try:
            sql = "delete from set_meal where user_id=%s and id=%s"

            db.delete(sql, (user_id,html_data['id']))

            sql1 = "select * from set_meal where  id=%s"
            if db.find_one(sql1, html_data['id']):
                data = {
                    'code': 400,
                    'message': '删除失败!'
                }
            else:
                data = {
                    'code': 200,
                    'message': '删除成功!'
                }
            return json(data)

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/setMeal/delete', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)
class setMealUpdate(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json

        try:
            sql = """
                   update set_meal set set_meal_money=%s,set_meal_shop=%s,title=%s,details=%s,set_meal_type=%s,set_meal_type_id=%s,sort=%s,image=%s,
                   JSONData=%s,status=%s,create_time=now() where id=%s; 
               """

            db.update(sql,(
                html_data['set_meal_money'] or '',
                html_data['set_meal_shop'] or '',
                html_data['title'] or '',
                html_data['details'] or '',
                html_data['set_meal_type'] or '',
                html_data['set_meal_type_id'] or '',
                html_data['sort'] or '',
                html_data['image'] or '',
                html_data['JSONData'] or '',
                html_data['status'] or '',
                html_data['id']
            ))

            return json({'code': 200, 'message': "修改成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/memberCharge/update', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)

class shoppingCartList(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        pageNum = int(request.args.get('pageNum'))
        pageSize = int(request.args.get('pageSize'))
        keyword = request.args.get('keyword', '')
        try:

            sql = """
               select id,goods_id,openid,goods_quantity,goods_price,goods_name,goods_image,goods_sku,goods_subtitle,status,ctime from goods_shopping_cart where merchant_id=%s
            """
            tol = f""" SELECT COUNT(*) FROM goods_shopping_cart where merchant_id='{user_id}' """
            if keyword:
                sql += f" and  goods_name LIKE '%{keyword}%' "
                tol += f" and  goods_name LIKE '%{keyword}%' "
            shoppingsql = sqlOrder(sql)
            sql = sqlPaging(pageNum, pageSize, shoppingsql)
            tol_data = db.find_one(tol)
            data = db.find_all(sql,(user_id))

            data = ProJosn(data,sql)

            return json({'code': 200, 'message': "请求成功!",'data':{
                'list':data,
                'total':tol_data[0]
            }})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/shoppingCartList/list', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)

class shoppingCartAdd(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json

        try:

            sql = """
                insert into goods_shopping_cart(goods_id,merchant_id,openid,goods_quantity,goods_price,goods_name,goods_image,goods_sku,goods_subtitle,status,ctime ) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,now()) 
            """
            db.insert(sql,(

                html_data['goods_id'] or '',
                user_id,
                html_data['openid'] or '',
                html_data['goods_quantity'] or '',
                html_data['goods_price'] or '',
                html_data['goods_name'] or '',
                html_data['goods_image'] or '',
                html_data['goods_sku'] or '',
                html_data['goods_subtitle'] or '',
                set_status(html_data['status']) or '',
            ))
            return json({'code': 200, 'message': "添加成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/shoppingCartAdd/add', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)

class shoppingCartDelete(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json

        try:
            sql = "delete from goods_shopping_cart where merchant_id=%s and id=%s"

            db.delete(sql, (user_id,html_data['id']))

            sql1 = "select * from goods_shopping_cart where  id=%s"
            if db.find_one(sql1, html_data['id']):
                data = {
                    'code': 400,
                    'message': '删除失败!'
                }
            else:
                data = {
                    'code': 200,
                    'message': '删除成功!'
                }
            return json(data)

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/shoppingCartDelete/delete', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)

class a_AiConfig_add(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json
        ai_uuid = Random_id(32,"AIUUID")
        try:
            sql_find = f"""
                select * from a_ai_config where merchant_id='{user_id}' and ai_type='{html_data['ai_type']}'
            """
            if db.find_one(sql_find):
                return json({'code': 201, 'message': "官网提供的不能多配置!"})

            sql = """
                    insert into a_ai_config(widthHeightType,merchant_type,width,height,max_tokens,top_k,temperature,stream,ai_type,ai_APPID,ai_APISecret,ai_APIKEY,merchant_id,ai_uuid,ai_memo,status,ctime ) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,now()) 
                """
            stream = 0
            if set_status(html_data['stream']):
                stream = 1

            db.insert(sql, (
                (html_data['widthHeightType']) or '',
                (html_data['merchant_type']) or '',
                int(html_data['width']) or '',
                int(html_data['height']) or '',
                int(html_data['max_tokens']) or '',
                int(html_data['top_k']) or '',
                float(html_data['temperature']),
                stream,
                html_data['ai_type'] or '',
                html_data['ai_APPID'] or '',
                html_data['ai_APISecret'] or '',
                html_data['ai_APIKEY'] or '',
                user_id,
                ai_uuid,
                html_data['ai_memo'] or '',
                'destroy'
            ))
            return json({'code': 200, 'message': "添加成功!"})
        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/a_AiConfig/list', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)

class a_AiConfig_list(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        pageNum = int(request.args.get('pageNum'))
        pageSize = int(request.args.get('pageSize'))
        keyword = request.args.get('keyword', '')
        try:

            sql = """
               select widthHeightType,id,merchant_type,height,width,max_tokens,top_k,ai_type,temperature,stream,ai_uuid,ai_type,ai_APPID,ai_APISecret,ai_APIKEY,ai_memo,status,ctime from a_ai_config where merchant_id=%s
            """
            tol = f""" SELECT COUNT(*) FROM a_ai_config where merchant_id='{user_id}' """
            if keyword:
                sql += f" and  ai_uuid LIKE '%{keyword}%' "
                tol += f" and  ai_uuid LIKE '%{keyword}%' "
            shoppingsql = sqlOrder(sql)
            sql = sqlPaging(pageNum, pageSize, shoppingsql)
            tol_data = db.find_one(tol)
            data = db.find_all(sql,(user_id))

            data = ProJosn(data,sql)

            return json({'code': 200, 'message': "请求成功!",'data':{
                'list':data,
                'total':tol_data[0]
            }})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/a_AiConfig_list/list', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)

class a_AiConfig_update(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json

        try:

            if set_status(html_data['status']) == 'normal':
                sql = """
                       update a_ai_config set status=%s where merchant_id=%s and ai_type=%s; 
                   """
                db.update(sql, (
                    'destroy',
                    user_id,
                    html_data['ai_type']
                ))
            stream = 0
            height = 0
            width = 0
            if set_status(html_data['stream']):
                stream = 1
            if html_data['height']:
                height = int(html_data['height'])
            if html_data['width']:
                width = int(html_data['width'])
            if set_status(html_data['stream']):
                stream = 1
            sql = """
                   update a_ai_config set widthHeightType=%s,merchant_type=%s,height=%s,width=%s,max_tokens=%s,top_k=%s,temperature=%s,stream=%s,ai_type=%s,ai_APPID=%s,ai_APISecret=%s,ai_APIKEY=%s,ai_memo=%s,status=%s,ctime=now() where id=%s; 
               """
            db.update(sql,(
                (html_data['widthHeightType']) or '',
                (html_data['merchant_type']) or '',
                height,
                width,
                int(html_data['max_tokens']) or 0,
                int(html_data['top_k']) or '',
                float(html_data['temperature']) or '',
                stream or '',
                html_data['ai_type'] or '',
                html_data['ai_APPID'] or '',
                html_data['ai_APISecret'] or '',
                html_data['ai_APIKEY'] or '',
                html_data['ai_memo'] or '',
                set_status(html_data['status']) or '',
                html_data['id']
            ))
            return json({'code': 200, 'message': "修改成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/a_AiConfig_update/update', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)

class a_AiConfig_delete(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json

        try:
            sql = "delete from a_ai_config where merchant_id=%s and id=%s"

            db.delete(sql, (user_id,html_data['id']))

            sql1 = "select * from a_ai_config where  id=%s"
            if db.find_one(sql1, html_data['id']):
                data = {
                    'code': 400,
                    'message': '删除失败!'
                }
            else:
                data = {
                    'code': 200,
                    'message': '删除成功!'
                }
            return json(data)

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/setMeal/delete', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)
class getSparkDesk(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        pageNum = int(request.args.get('pageNum'))
        pageSize = int(request.args.get('pageSize'))
        keyword = request.args.get('keyword', '')
        try:
            # JOIN goods on goods_order.goods_id=goods.goods_id
            sql = f"""
               SELECT ai_spark_desk.id,ai_spark_desk.AIid,ai_spark_desk.openid,ai_spark_desk.content,ai_spark_desk.keyword,ai_spark_desk.phone,ai_spark_desk.nickName,ai_data_all.cost,ai_data_all.preview,ai_data_all.likes,ai_data_all.recommend,ai_data_all.ctime
            from ai_spark_desk join ai_data_all on ai_spark_desk.AIid=ai_data_all.AIid where ai_spark_desk.merchant_id='{user_id}'
            """
            tol = f""" SELECT COUNT(*) from ai_spark_desk join ai_data_all on ai_spark_desk.AIid=ai_data_all.AIid where ai_spark_desk.merchant_id='{user_id}' """
            if keyword:
                sql += f" and  ai_spark_desk.keyword LIKE '%{keyword}%' "
                tol += f" and  ai_spark_desk.keyword LIKE '%{keyword}%' "
            shoppingsql = sqlOrder(sql)
            sql = sqlPaging(pageNum, pageSize, shoppingsql)
            tol_data = db.find_one(tol)
            data = db.find_all(sql)

            data = ProJosn(data,[
                'id','AIid','openid','content','keyword','phone','nickName','cost','preview','likes','recommend','ctime'
            ],'list')

            return json({'code': 200, 'message': "请求成功!",'data':{
                'list':data,
                'total':tol_data[0]
            }})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/ai_spark_desk/list', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)
class SparkDeskDelete(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json

        try:
            sql = "delete from ai_spark_desk where merchant_id=%s and AIid=%s"
            sql1 = "delete from ai_data_all where merchant_id=%s and AIid=%s"
            db.delete(sql, (user_id,int(html_data['AIid'])))
            db.delete(sql1, (user_id, int(html_data['AIid'])))

            data = {
                'code': 200,
                'message': '删除成功!'
            }
            return json(data)

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/setMeal/delete', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)
class getAIPicture(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        pageNum = int(request.args.get('pageNum'))
        pageSize = int(request.args.get('pageSize'))
        keyword = request.args.get('keyword', '')
        try:
            # JOIN goods on goods_order.goods_id=goods.goods_id
            sql = f"""
               SELECT ai_data_all.search_content,file_manage.url,file_manage.openid,file_manage.AIid,ai_data_all.cost,ai_data_all.picture_width,ai_data_all.picture_height,
            ai_data_all.preview,ai_data_all.likes,ai_data_all.recommend,ai_data_all.ctime from file_manage join ai_data_all on file_manage.AIid=ai_data_all.AIid 
            where file_manage.merchant_id='{user_id}' and file_manage.type='AI'
            """
            tol = f""" SELECT COUNT(*) from file_manage join ai_data_all on file_manage.AIid=ai_data_all.AIid 
            where file_manage.merchant_id='{user_id}' and file_manage.type='AI' """
            if keyword:
                sql += f" and  ai_data_all.search_content LIKE '%{keyword}%' "
                tol += f" and  ai_data_all.search_content LIKE '%{keyword}%' "
            shoppingsql = sqlOrder(sql)
            sql = sqlPaging(pageNum, pageSize, shoppingsql)
            tol_data = db.find_one(tol)
            data = db.find_all(sql)

            data = ProJosn(data,[
                'search_content','url','openid','AIid','cost','picture_width','picture_height','preview','likes','recommend','ctime'
            ],'list')

            return json({'code': 200, 'message': "请求成功!",'data':{
                'list':data,
                'total':tol_data[0]
            }})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/ai_spark_desk/list', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)
class AIPictureDelete(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json

        try:
            sql = "delete from file_manage where merchant_id=%s and AIid=%s"
            sql1 = "delete from ai_data_all where merchant_id=%s and AIid=%s"
            db.delete(sql, (user_id,int(html_data['AIid'])))
            db.delete(sql1, (user_id, int(html_data['AIid'])))

            data = {
                'code': 200,
                'message': '删除成功!'
            }
            return json(data)

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/SparkDeskDelete/delete', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)

class AIPictureUpdate(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json
        try:
            sql = """
                   update ai_data_all set recommend=%s where AIid=%s; 
               """
            db.update(sql,(
                int(html_data['recommend']),
                int(html_data['AIid'])
            ))

            return json({'code': 200, 'message': "修改成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/memberCharge/update', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)
# 优惠券
class couponsAdd(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json
        # 是否是指定商品
        goods_data_dict = ''
        if html_data['item_id']:
            sql_goods = f"""
                select goodsName,goodsDetailsJson,goodsPrice,previewUrl from goods where goods_id='{html_data['item_id']}'
            """
            goods_data = db.find_one(sql_goods)
            goods_data_dict = {
                'goodsName':goods_data[0],
                'goodsDetailsJson':goods_data[1],
                'goodsPrice':goods_data[2],
                'previewUrl':goods_data[3],
            }
        try:
            sql = """
                insert into coupons(image,item_id,item_dict,user_number,startTime,endTime,merchant_id,plugin_id,title,type,score,moneys,min_money,max_number,numbers,content,status,getCondition,ctime) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,now()) 
            """

            score = 0
            min_money = 0
            if html_data['score']:
                score = int(html_data['score'])
            if html_data['min_money'] != '' or html_data['min_money']:
                min_money = int(html_data['min_money'])

            if html_data['condition'] == '弹窗发放' or html_data['condition'] == '新人发放':
                sql_status = f"""
                      update coupons set status='0' where status='1' and (getCondition='新人发放' or getCondition='弹窗发放') and merchant_id='{user_id}'
                """
                db.update(sql_status)
            db.insert(sql,(
                html_data['image'] or '',
                html_data['item_id'] or '',
                jn.dumps(goods_data_dict) or '',
                0,
                timestamp_to_standard(html_data['startTime']) or '',
                timestamp_to_standard(html_data['endTime']) or '',
                user_id,
                html_data['plugin_id'] or '',
                html_data['title'] or '',
                int(html_data['type']) or '',
                score,
                int(html_data['moneys']) or '',
                min_money,
                int(html_data['max_number']) or '',
                int(html_data['numbers']) or '',
                # int(html_data['user_number']) or '',
                # int(html_data['user_use']) or '',
                html_data['content'] or '',
                '1',
                html_data['condition'] or '',
            ))
            return json({'code': 200, 'message': "添加成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/couponsAdd/add', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)
class couponsList(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        pageNum = int(request.args.get('pageNum'))
        pageSize = int(request.args.get('pageSize'))
        keyword = request.args.get('keyword', '')
        try:
            sql = """
               select image,item_id,item_dict,startTime,endTime,getCondition,id,title,type,score,moneys,min_money,max_number,numbers,user_number,user_use,content,businessId,status,ctime from coupons where merchant_id=%s
            """
            tol = f""" SELECT COUNT(*) FROM coupons where merchant_id='{user_id}' """
            if keyword:
                sql += f" and  title LIKE '%{keyword}%' "
                tol += f" and  title LIKE '%{keyword}%' "
            shoppingsql = sqlOrder(sql)
            sql = sqlPaging(pageNum, pageSize, shoppingsql)
            tol_data = db.find_one(tol)
            data = db.find_all(sql,(user_id))

            data = ProJosn(data,['image','item_id','item_dict','startTime','endTime','condition','id','title','type','score','moneys','min_money','max_number','numbers','user_number','user_use','content','businessId','_status','ctime'],'list')

            return json({'code': 200, 'message': "请求成功!",'data':{
                'list':data,
                'total':tol_data[0]
            }})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/couponsList/list', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)
class couponsUpdate(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json

        if html_data['status']:
            _status='1'
        else:
            _status = '0'
        goods_data_dict = ''

        if html_data['item_id']!='':
            sql_goods = f"""
                select goodsName,goodsDetailsJson,goodsPrice,previewUrl from goods where goods_id='{html_data['item_id']}'
            """
            goods_data = db.find_one(sql_goods)
            goods_data_dict = {
                'goodsName':goods_data[0],
                'goodsDetailsJson':goods_data[1],
                'goodsPrice':goods_data[2],
                'previewUrl':goods_data[3],
            }

        if html_data['condition'] == '弹窗发放' or html_data['condition'] == '新人发放':
            sql_status = f"""
                  update coupons set status='0' where status='1' and (getCondition='新人发放' or getCondition='弹窗发放') and merchant_id='{user_id}'
            """
            db.update(sql_status)

        try:
            score = 0
            min_money = 0

            if html_data['score'] and (html_data['score'])!=0 and html_data['score']!='0' and  html_data['score']!='':
                score = int(html_data['score'])
            if html_data['min_money'] and  html_data['min_money']!=0 and html_data['min_money']!='0' and  html_data['min_money']!='':
                min_money = int(html_data['min_money'])

            sql = """
                   update coupons set image=%s,startTime=%s,endTime=%s,item_id=%s,item_dict=%s,getCondition=%s,status=%s,title=%s,type=%s,score=%s,moneys=%s,min_money=%s,max_number=%s,numbers=%s,content=%s,ctime=now() where id=%s
               """
            db.update(sql,(
                (html_data['image']) or '',
                timestamp_to_standard(html_data['startTime']) or '',
                timestamp_to_standard(html_data['endTime']) or '',
                (html_data['item_id']) or '',
                jn.dumps(goods_data_dict) or '',
                (html_data['condition']) or '',
                _status,
                (html_data['title']) or '',
                int(html_data['type']) or '',
                score,
                int(html_data['moneys']) or '',
                min_money,
                int(html_data['max_number']) or '',
                int(html_data['numbers']) or '',
                (html_data['content']) or '',
                int(html_data['id'])
            ))
            return json({'code': 200, 'message': "修改成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/couponsUpdate/update', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)
class couponsDelete(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json

        try:
            sql = "delete from coupons where merchant_id=%s and id=%s"
            sql_my = "delete from my_coupons where merchant_id=%s and coupons_id=%s"
            db.delete(sql, (user_id,html_data['id']))
            db.delete(sql_my, (user_id, html_data['id']))
            sql1 = "select * from coupons where id=%s"
            if db.find_one(sql1, html_data['id']):
                data = {
                    'code': 400,
                    'message': '删除失败!'
                }
            else:
                data = {
                    'code': 200,
                    'message': '删除成功!'
                }
            return json(data)

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/shoppingCartDelete/delete', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)

class userCoupons(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        pageNum = int(request.args.get('pageNum'))
        pageSize = int(request.args.get('pageSize'))
        keyword = request.args.get('keyword', '')
        coupons_id = int(request.args.get('coupons_id', 0))
        try:
            sql = f"""
               select coupons.title,coupons.type,coupons.score,coupons.moneys,coupons.min_money,coupons.max_number,coupons.numbers,coupons.user_number,coupons.user_use,coupons.content,
               coupons.businessId,coupons.item_id,coupons.getCondition,coupons.startTime,coupons.endTime,coupons.item_dict,coupons.image,my_coupons.openid,my_coupons.ctime,
               my_coupons.status,my_coupons.utime from coupons join my_coupons on coupons.id=my_coupons.coupons_id where 
               my_coupons.merchant_id='{user_id}'
            """
            if coupons_id != 0:
                sql += f" and my_coupons.coupons_id = {coupons_id} "

            tol = f""" SELECT COUNT(*) from coupons join my_coupons on coupons.id=my_coupons.coupons_id where 
               my_coupons.merchant_id='{user_id}' and my_coupons.coupons_id={coupons_id} """
            if keyword:
                sql += f" and  coupons.title LIKE '%{keyword}%' "
                tol += f" and  coupons.title LIKE '%{keyword}%' "
            shoppingsql = sqlOrder(sql)
            sql = sqlPaging(pageNum, pageSize, shoppingsql)
            tol_data = db.find_one(tol)
            data = db.find_all(sql)

            data = ProJosn(data,['title','type','score','moneys','min_money','max_number','numbers','user_number','user_use','content','businessId','item_id','getCondition','startTime','endTime',
                                 'item_dict','image','openid','ctime','userStatus','utime'],'list')

            return json({'code': 200, 'message': "请求成功!",'data':{
                'list':data,
                'total':tol_data[0]
            }})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/userCoupons', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)

# 签到配置列表
class sign_in_list(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        pageNum = int(request.args.get('pageNum'))
        pageSize = int(request.args.get('pageSize'))
        keyword = request.args.get('keyword', '')
        try:
            sql = """
               select id,title,image,sort,reward_id,content,sign_in_mode,sign_in_send,reward_type,sort,status,ctime,startTime,endTime,number_day from sign_in where merchant_id=%s
            """
            tol = f""" SELECT COUNT(*) FROM sign_in where merchant_id='{user_id}' """
            if keyword:
                sql += f" and  title LIKE '%{keyword}%' "
                tol += f" and  title LIKE '%{keyword}%' "
            shoppingsql = sqlOrder(sql,'sort','ASC')
            sql = sqlPaging(pageNum, pageSize, shoppingsql)
            tol_data = db.find_one(tol)
            data = db.find_all(sql,(user_id))
            data = ProJosn(data, sql)
            return json({'code': 200, 'message': "请求成功!",'data':{
                'list':data,
                'total':tol_data[0]
            }})
        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/sign_in_list/list', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)

# 添加签到配置
class sign_in_add(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json

        try:
            sql = """
                insert into sign_in(merchant_id,number_day,title,image,sort,reward_id,content,sign_in_mode,sign_in_send,reward_type,status,startTime,endTime,ctime) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,now()) 
            """
            if html_data['status']:
                status = '1'
            else:
                status = '0'

            if html_data['sign_in_send']:
                sign_in_send = '1'
            else:
                sign_in_send = '0'


            db.insert(sql,(
                user_id,
                int(html_data['number_day']) or 0,
                html_data['title'] or '',
                html_data['image'] or '',
                int(html_data['sort']) or 0,
                int(html_data['reward_id'] )or '',
                html_data['content'] or '',
                html_data['sign_in_mode'] or '',
                sign_in_send or '',
                html_data['reward_type'] or '',
                status or '0',
                timestamp_to_standard(html_data['startTime']) or '',
                timestamp_to_standard(html_data['endTime']) or '',
            ))
            return json({'code': 200, 'message': "添加成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/sign_in_add', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)

class sign_in_update(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json
        try:
            sql = """
                   update sign_in set number_day=%s,title=%s,image=%s,sort=%s,reward_id=%s,content=%s,sign_in_mode=%s,sign_in_send=%s,reward_type=%s,status=%s,startTime=%s,endTime=%s where id=%s
               """
            if html_data['status']:
                status = '1'
            else:
                status = '0'

            if html_data['sign_in_send']:
                sign_in_send = '1'
            else:
                sign_in_send = '0'

            if html_data['sort']:
                sort = int(html_data['sort'])
            else:
                sort = 0

            db.update(sql,(
                html_data['number_day'] or 0,
                html_data['title'] or '',
                html_data['image'] or '',
                sort or 0,
                html_data['reward_id'] or 0,
                html_data['content'] or '',
                html_data['sign_in_mode'] or '',
                sign_in_send or '',
                html_data['reward_type'] or '',
                status,
                timestamp_to_standard(html_data['startTime']) or '',
                timestamp_to_standard(html_data['endTime']) or '',
                (html_data['id'])
            ))
            return json({'code': 200, 'message': "修改成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/sign_in_update', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)

class sign_in_delete(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json

        try:
            sql = "delete from sign_in where merchant_id=%s and id=%s"
            db.delete(sql, (user_id,html_data['id']))
            sql1 = "select * from sign_in where id=%s"
            if db.find_one(sql1, html_data['id']):
                data = {
                    'code': 400,
                    'message': '删除失败!'
                }
            else:
                data = {
                    'code': 200,
                    'message': '删除成功!'
                }
            return json(data)

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/sign_in_delete', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)


# 作品展示
class showWorks_list(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        pageNum = int(request.args.get('pageNum'))
        pageSize = int(request.args.get('pageSize'))
        keyword = request.args.get('keyword', '')
        try:
            sql = """
               select id,title,introduce,label_dict,author,sort,startTime,animation_dict,technology_dict,git,url,type,slideshow,ctime,status from showWorks where merchant_id=%s
            """
            tol = f""" SELECT COUNT(*) FROM showWorks where merchant_id='{user_id}' """
            if keyword:
                sql += f" and  title LIKE '%{keyword}%' "
                tol += f" and  title LIKE '%{keyword}%' "
            shoppingsql = sqlOrder(sql,'sort','ASC')
            sql = sqlPaging(pageNum, pageSize, shoppingsql)
            tol_data = db.find_one(tol)
            data = db.find_all(sql,(user_id))
            data = ProJosn(data, sql)
            return json({'code': 200, 'message': "请求成功!",'data':{
                'list':data,
                'total':tol_data[0]
            }})
        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/showWorks_list/list', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)


# 添加作品展示
class showWorks_add(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json

        try:
            sql = """
                insert into showWorks(merchant_id,title,introduce,label_dict,author,sort,startTime,animation_dict,technology_dict,git,url,type,slideshow,status,ctime) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,now()) 
            """
            if html_data['status']:
                status = '1'
            else:
                status = '0'

            db.insert(sql,(
                user_id,
                html_data['title'] or '',
                html_data['introduce'] or '',
                html_data['label_dict'] or '',
                html_data['author'] or '',
                int(html_data['sort']) or 0,
                timestamp_to_standard(html_data['startTime']) or '1999-01-01 00:00:00',
                (html_data['animation_dict']) or '',
                (html_data['technology_dict']) or '',
                (html_data['git']) or '',
                (html_data['url']) or '',
                (html_data['type']) or '',
                (html_data['slideshow']) or '',
                status or '0',

            ))
            return json({'code': 200, 'message': "添加成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/showWorks_add', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)

# 编辑作品展示
class showWorks_edit(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json
        try:
            sql = """
                   update showWorks set title=%s,introduce=%s,label_dict=%s,author=%s,sort=%s,startTime=%s,animation_dict=%s,technology_dict=%s,git=%s,url=%s,type=%s,slideshow=%s,status=%s where id=%s
               """
            if html_data['status']:
                status = '1'
            else:
                status = '0'

            if html_data['sort']:
                sort = int(html_data['sort'])
            else:
                sort = 0

            db.update(sql,(
                html_data['title'] or '',
                html_data['introduce'] or '',
                html_data['label_dict'] or '',
                html_data['author'] or '',
                sort or 0,
                timestamp_to_standard(html_data['startTime']) or '',
                html_data['animation_dict'] or '',
                html_data['technology_dict'] or '',
                html_data['git'] or '',
                html_data['url'] or '',
                html_data['type'] or '',
                html_data['slideshow'] or '',
                status or '',
                (html_data['id'])
            ))
            return json({'code': 200, 'message': "修改成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/sign_in_update', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)


class showWorks_delete(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json

        try:
            sql = "delete from showWorks where merchant_id=%s and id=%s"

            db.delete(sql, (user_id,html_data['id']))
            sql1 = "select * from showWorks where id=%s"
            if db.find_one(sql1, html_data['id']):
                data = {
                    'code': 400,
                    'message': '删除失败!'
                }
            else:
                data = {
                    'code': 200,
                    'message': '删除成功!'
                }
            return json(data)

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/shoppingCartDelete/delete', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)